563. 二叉树的坡度
https://leetcode-cn.com/problems/binary-tree-tilt/
- 提交时间:2021-11-18 14:27:15
- 执行用时:20 ms, 在所有 Go 提交中击败了13.71%的用户
- 内存消耗:6.4 MB, 在所有 Go 提交中击败了54.84%的用户
- 通过测试用例:77 / 77
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func findTilt(root *TreeNode) int {
if root == nil {
return 0
}
return findTilt(root.Left) + findTilt(root.Right) + abs(treeSum(root.Left) - treeSum(root.Right))
}
func treeSum(node *TreeNode) int {
if node == nil {
return 0
}
return node.Val + treeSum(node.Left) + treeSum(node.Right)
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}